<?php
/*
 * Copyright 2009, Jeffrey Palm.
 */

include_once 'settings.php';

/*
 * General utility stuff that every file could probably use.  As we
 * write and build this, we may want to move 'generic' stuff
 * elsewhere, too.  i.e. maybe we want to put all the functions
 * basically just hitting teh DB in one file.  I don't know.
 */

/**
 * Wraps 's' in single quotes.
 */
function qw($s) {
	//$s = preg_replace("/'/","\\'",$s);
	$s = preg_replace("/\"/","\\\"",$s);
	$s = preg_replace("/`/","",$s);
	$s = preg_replace("/\t/"," ",$s);
	$s = preg_replace("/\r/","",$s);
	$s = preg_replace("/\n/","",$s);
	return "'" . $s . "'";
}

/**
 * Performs a query with the passed in MySQL and returns the result.
 */
function sql_query($sql) {
	global $db;
	$result = mysql_db_query(DB_NAME,$sql,$db);
	if (!$result) {
		echo("ERROR: " . mysql_error() . "\n$sql\n");
	}
	return $result;
}

/**
 * Returns one row of the executed query on the MySQL statement 'sql'.
 */
function sql_row($sql) {
  return mysql_fetch_array(sql_query($sql));
}

/**
 * Returns the *required* parameter with key 'key'.  We die if this
 * value is not set.
 */
function param($key) {
  if (!isset($_REQUEST[$key])) {
    die('Required param: ' . $key);
  }
  return $_REQUEST[$key];
}

/**
 * Sets the Content-type to text/plain.
 */
function textHeader() {
  header('Content-type: text/plain');
}

/**
 * Echoes out a newline character.
 */
function newline() {
  echo "\n";
}

/**
 * Shortcut for newline().
 */
function n() {
  newline();
}

/**
 * Prints 'msg' and a new line.
 */
function outln($msg) {
	echo $msg;
	echo "\n";
}

/**
 * Generates one random character.  Stole this from paypal.
 */
function generateCharacter () {
	$possible = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	$char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
	return $char;
}

/**
 * Creates a fresh, unique key that will identify devices
 * around. Right now, just make a big fucking ugly, String, perhaps
 * check to see that it's already in there.
 */
function createNewSharedKey() {
	$res = '';
	for ($i=0; $i<SHARED_KEY_LENGTH; $i++) {
		$res .= generateCharacter();
	}
	return $res;
}

/**
 * Creates a new shared key for this user, inerts them into the
 * 'devices' table, and returns the shared key.
 */
function createAndInsertNewSharedKey($user) {
	note('Creating a new key');
	$shared_key = createNewSharedKey();
	$sql = 'INSERT into `devices` (user,shared_key,date_created) VALUES ('
		.    qw($user) . ','
		.    qw($shared_key) . ','
		.    qw(timestamp())
		.    ')';
		;
	sql_query($sql);
	return $shared_key;
}

/**
 * Looks up the device for this user and returns the shared key or
 * 'NULL' if we don't have this user yet in the 'devices' table.
 */
function getSharedKeyForUser($user) {
	
	$sql = 'SELECT * FROM `devices` WHERE `user` = ' . qw($user);
	$row = sql_row($sql);

	// If we have such a user, return their shared key
	if ($row) {
		note('Found the key');
		return $row['shared_key'];
	}

	// Not in the system yet
	return NULL;
}

/**
 * Prints a little message out, with a '#' in front, to we know to
 * ignore it.
 */
function note($msg) {
  echo '# [' . datetime() . '] ' . $msg . "\n";
}

/**
 * Gives you a time stamp.  I need to look at these two names!
 */
function datetime() {
  $DATE_FORMAT = "Y-m-d H:i:s";
  return date($DATE_FORMAT);
}

/**
 * Seconds past some time.
 */
function timestamp() {
	list($usec, $sec) = explode(" ", microtime());
	return $sec;
}

?>